package de.baumann.browser.api.net.base;

import android.accounts.NetworkErrorException;
import android.util.Log;

import java.util.concurrent.TimeUnit;

import de.baumann.browser.OdinApplication;
import de.baumann.browser.utils.NetworkUtils;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.ResponseBody;

public class RetryWithDelay implements Function<Observable<Throwable>, Observable<?>> {

    private final int maxRetries;
    private final int retryDelayMillis;
    private int retryCount;

    public RetryWithDelay(int maxRetries, int retryDelayMillis) {
        this.maxRetries = maxRetries;
        this.retryDelayMillis = retryDelayMillis;
    }

    @Override
    public Observable<?> apply(Observable<Throwable> throwableObservable) throws Exception {
        return throwableObservable
                .flatMap((Function<Throwable, ObservableSource<?>>) throwable -> {

                    if (!NetworkUtils.isNetWorkAvailable(OdinApplication.getInstance())){
                        return Observable.error(new NetworkErrorException("网络不可用"));
                    }

                    if (++retryCount <= maxRetries) {
                        Log.e("get error", "it will try after " + retryDelayMillis * retryCount + " millisecond, retry count " + retryCount);
                        return Observable.timer(retryDelayMillis, TimeUnit.MILLISECONDS);
                    }
                    return Observable.error(throwable);
                });
    }
}
